import React, { useState, useRef, useEffect } from 'react';
import { Input, AutoComplete, Tag, Space } from 'antd';
import { DatabaseOutlined, UserOutlined, MailOutlined } from '@ant-design/icons';
import type { AutoCompleteProps } from 'antd';

const { TextArea } = Input;

interface Variable {
  name: string;
  display_name: string;
  field_type: string;
  is_email: boolean;
  is_name: boolean;
  sample_value?: string;
}

interface SmartEditorProps {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  variables?: Variable[];
  rows?: number;
  disabled?: boolean;
}

const SmartEditor: React.FC<SmartEditorProps> = ({
  value = '',
  onChange,
  placeholder = '输入内容，使用 {{变量名}} 插入动态数据',
  variables = [],
  rows = 6,
  disabled = false,
}) => {
  const [inputValue, setInputValue] = useState(value);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [suggestions, setSuggestions] = useState<AutoCompleteProps['options']>([]);
  const [cursorPosition, setCursorPosition] = useState(0);
  const textAreaRef = useRef<any>(null);

  useEffect(() => {
    setInputValue(value);
  }, [value]);

  // 检测是否在输入变量
  const checkForVariableInput = (text: string, position: number) => {
    const beforeCursor = text.substring(0, position);
    const match = beforeCursor.match(/\{\{([^}]*)$/);
    
    if (match) {
      const query = match[1].toLowerCase();
      const filteredVariables = variables.filter(variable =>
        variable.name.toLowerCase().includes(query) ||
        variable.display_name.toLowerCase().includes(query)
      );

      const options = filteredVariables.map(variable => ({
        value: variable.name,
        label: (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Space>
              {variable.is_email && <MailOutlined style={{ color: '#1890ff' }} />}
              {variable.is_name && <UserOutlined style={{ color: '#52c41a' }} />}
              {!variable.is_email && !variable.is_name && <DatabaseOutlined style={{ color: '#666' }} />}
              <span>{variable.display_name || variable.name}</span>
            </Space>
            <Space>
              <Tag size="small" color={getFieldTypeColor(variable.field_type)}>
                {getFieldTypeLabel(variable.field_type)}
              </Tag>
              {variable.sample_value && (
                <span style={{ fontSize: '12px', color: '#999' }}>
                  示例: {variable.sample_value}
                </span>
              )}
            </Space>
          </div>
        ),
      }));

      setSuggestions(options);
      setShowSuggestions(true);
      return true;
    }

    setShowSuggestions(false);
    return false;
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newValue = e.target.value;
    const position = e.target.selectionStart || 0;
    
    setInputValue(newValue);
    setCursorPosition(position);
    onChange?.(newValue);

    // 检查是否需要显示变量建议
    checkForVariableInput(newValue, position);
  };

  const handleVariableSelect = (variableName: string) => {
    const beforeCursor = inputValue.substring(0, cursorPosition);
    const afterCursor = inputValue.substring(cursorPosition);
    
    // 找到 {{ 的位置
    const match = beforeCursor.match(/\{\{([^}]*)$/);
    if (match) {
      const startPos = beforeCursor.length - match[0].length;
      const newValue = 
        inputValue.substring(0, startPos) + 
        `{{${variableName}}}` + 
        afterCursor;
      
      setInputValue(newValue);
      onChange?.(newValue);
      setShowSuggestions(false);

      // 设置光标位置到变量后面
      setTimeout(() => {
        if (textAreaRef.current) {
          const newCursorPos = startPos + `{{${variableName}}}`.length;
          textAreaRef.current.focus();
          textAreaRef.current.setSelectionRange(newCursorPos, newCursorPos);
        }
      }, 0);
    }
  };

  const insertVariable = (variableName: string) => {
    const textarea = textAreaRef.current?.resizableTextArea?.textArea;
    if (!textarea) return;

    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const newValue = 
      inputValue.substring(0, start) + 
      `{{${variableName}}}` + 
      inputValue.substring(end);
    
    setInputValue(newValue);
    onChange?.(newValue);

    // 设置光标位置
    setTimeout(() => {
      const newCursorPos = start + `{{${variableName}}}`.length;
      textarea.focus();
      textarea.setSelectionRange(newCursorPos, newCursorPos);
    }, 0);
  };

  const getFieldTypeColor = (type: string) => {
    switch (type) {
      case 'string': return 'blue';
      case 'number': return 'green';
      case 'date': return 'orange';
      case 'boolean': return 'purple';
      case 'email': return 'cyan';
      default: return 'default';
    }
  };

  const getFieldTypeLabel = (type: string) => {
    switch (type) {
      case 'string': return '文本';
      case 'number': return '数字';
      case 'date': return '日期';
      case 'boolean': return '布尔';
      case 'email': return '邮箱';
      default: return type;
    }
  };

  return (
    <div style={{ position: 'relative' }}>
      <TextArea
        ref={textAreaRef}
        value={inputValue}
        onChange={handleInputChange}
        placeholder={placeholder}
        rows={rows}
        disabled={disabled}
        style={{ fontFamily: 'monospace' }}
      />
      
      {showSuggestions && suggestions && suggestions.length > 0 && (
        <div
          style={{
            position: 'absolute',
            top: '100%',
            left: 0,
            right: 0,
            zIndex: 1000,
            backgroundColor: 'white',
            border: '1px solid #d9d9d9',
            borderRadius: '6px',
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
            maxHeight: '200px',
            overflowY: 'auto',
          }}
        >
          {suggestions.map((option, index) => (
            <div
              key={option.value}
              style={{
                padding: '8px 12px',
                cursor: 'pointer',
                borderBottom: index < suggestions.length - 1 ? '1px solid #f0f0f0' : 'none',
              }}
              onMouseDown={(e) => {
                e.preventDefault();
                handleVariableSelect(option.value as string);
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#f5f5f5';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'white';
              }}
            >
              {option.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// 导出插入变量的工具函数，供外部组件使用
export const insertVariableIntoEditor = (
  textAreaRef: React.RefObject<any>,
  variableName: string,
  currentValue: string,
  onChange: (value: string) => void
) => {
  const textarea = textAreaRef.current?.resizableTextArea?.textArea;
  if (!textarea) return;

  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const newValue = 
    currentValue.substring(0, start) + 
    `{{${variableName}}}` + 
    currentValue.substring(end);
  
  onChange(newValue);

  // 设置光标位置
  setTimeout(() => {
    const newCursorPos = start + `{{${variableName}}}`.length;
    textarea.focus();
    textarea.setSelectionRange(newCursorPos, newCursorPos);
  }, 0);
};

export default SmartEditor;
